/**************************************************
 * Project Name         [JavaEE_XML]
 * File Name            [Dom4jParseXML.java]
 * Creation Date        [08-19-2014]
 * 
 * Copyright© ge.y.yang@gmail.com All Rights Reserved
 * 
 * Work hard, play harder, think big and keep fit
 **************************************************/
package pkg_03_dom4j;

import java.io.File;
import java.util.List;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.Text;
import org.dom4j.VisitorSupport;
import org.dom4j.io.SAXReader;

/**
 * 
 * @author 不落的太阳(Sean Yang)
 * @version 1.0
 * @since JDK 6
 * 
 */
public class Dom4jParseXML {

	/**
	 * 使用普通模式遍历DOM树
	 * 
	 * @param documentName
	 * @throws DocumentException
	 */
	public void parseXML1(String documentPath) throws DocumentException {
		SAXReader xmlReader = new SAXReader();
		Document document = xmlReader.read(new File(documentPath));
		// 获得根节点元素
		Element rootElement = document.getRootElement();
		treeWalk(rootElement);
	}

	private void treeWalk(Element element) {
		if (element.isRootElement())
			System.out.println("Root element=" + element.getName());
		for (int i = 0, size = element.nodeCount(); i < size; i++) {
			Node node = element.node(i);
			if (node instanceof Element) {
				Element e = (Element) node;
				System.out.print(e.getName() + "=" + e.getText());
				List<Attribute> attributes = e.attributes();
				for (int j = 0; attributes != null && j < attributes.size(); j++) {
					System.out.print(" Attribute["
							+ attributes.get(j).getName() + "="
							+ attributes.get(j).getValue() + "]");
				}
				System.out.println();
				treeWalk((Element) node);
			}
		}
	}

	/**
	 * 使用Visitor方式遍历DOM树
	 * 
	 * @param documentPath
	 * @throws DocumentException
	 */
	public void parseXML2(String documentPath) throws DocumentException {

		class MyVisitor extends VisitorSupport {
			@Override
			public void visit(Element element) {
				if (element.isRootElement()) {
					System.out.println(element.getName());
				} else {
					System.out.print(element.getName());
				}
			}

			@Override
			public void visit(Attribute attr) {
				System.out.println(" Attribute[" + attr.getName() + "="
						+ attr.getValue() + "]");
			}

			@Override
			public void visit(Text text) {
				System.out.println("=" + text.getStringValue());
			}
		}

		SAXReader xmlReader = new SAXReader();
		Document document = xmlReader.read(new File(documentPath));
		document.getRootElement().accept(new MyVisitor());

	}

	public static void main(String[] args) throws DocumentException {
		String documentPath = "src/xml/Student.xml";
		new Dom4jParseXML().parseXML1(documentPath);

		System.out.println();
		new Dom4jParseXML().parseXML2(documentPath);
	}

}
